package org.ch03.job.test07;

import java.lang.reflect.Field;

/**
 * @author XCH
 * @date 2025 - 03 - 28
 */
public class Student {
    private String name;
    @Sex(values = {"男", "女"}, message = "性别不符要求")
    private String sex;
    private String food;

    public Student() {
    }

    public Student(String name, String sex, String food) {
        this.name = name;
        try {
            checkSex(sex);
            this.sex = sex;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        this.food = food;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        try {
            checkSex(sex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.sex = sex;
    }

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", food='" + food + '\'' +
                '}';
    }
    public void checkSex(String sex) throws Exception {
        Field fields = this.getClass().getDeclaredField("sex");

        boolean flag = fields.isAnnotationPresent(Sex.class);
        if (!flag) {
            System.out.println("没有注解");
            return;
        }
        Sex annotation = fields.getAnnotation(Sex.class);
        if (annotation == null) {
            for (String value : annotation.values()) {
                if (sex.equals(value)) {
                    System.out.println("性别符合要求");
                    return;
                }
            }
            throw new Exception(annotation.message());
        }
    }
}
